﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MainService;
using Common;

namespace Web.Controllers
{
#pragma warning disable CS1591
  [Route("api/Open/[controller]")]
  public class AuthController : BaseController
  {
    public readonly IAuthService _AuthService;
    public AuthController(IAuthService AuthService)
    {
      _AuthService = AuthService;
    }
#pragma warning restore CS1591

    /// <summary>
    /// 获取 token
    /// </summary>
    /// <param name="Model"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> GetToken([FromBody] ParmGenToken Model)
    {
      var res = _AuthService.GenToken(Model.Wid);

      if (res.Success)
      {
        return await PublicTool.ReturnSuccess(res.Data);
      }
      else {
        return await PublicTool.ReturnError(res.ErrMsg);
      }      
    }

    /// <summary>
    /// 创建账号
    /// </summary>
    /// <param name="Model"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> CreateId([FromBody] ParmGenToken Model)
    {
      var resOfCreate = _AuthService.CreateId(Model);

      if (!resOfCreate.Success) return await PublicTool.ReturnError(resOfCreate.ErrMsg);
      
      var res = _AuthService.GenToken(Model.Wid);
      if (res.Success)
      {
        return await PublicTool.ReturnSuccess(res.Data);
      }
      else {
        return await PublicTool.ReturnError(res.ErrMsg);
      }       
     
    }


    /// <summary>
    /// GetOpenId接口传参
    /// </summary>
    public class ParmForGetOpenId
    {
      /// <summary>
      /// wx.login 返回的 code
      /// </summary>
      public string codes { get; set; }
      /// <summary>
      /// wx.GetUserInfo 返回的 encryptedData
      /// </summary>
      public string encryptedDataStr { get; set; }
      /// <summary>
      /// wx.GetUserInfo 返回的 iv
      /// </summary>
      public string iv { get; set; }
    }

    /// <summary>
    /// 获取微信Openid
    /// </summary>
    /// <param name="Model"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> GetOpenId([FromBody] ParmForGetOpenId Model)
    {
      OpenIdOfWxOpen res = _AuthService.GetOpenId(Model.codes, Model.encryptedDataStr, Model.iv);

      return await PublicTool.ReturnSuccess(res.unionid);
    }

    /// <summary>
    /// 获取手机号码
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    [HttpGet("[action]")]
    public async Task<IActionResult> GetPhoneNum(string code)
    {
      return await PublicTool.ReturnSuccess(_AuthService.GetPhoneNum(code));
    }
  }
}
